<?php
namespace app\common\library;
use app\admin\model\SystemMenu;
use app\admin\service\TriggerService;
use app\common\constants\MenuConstant;
use think\Exception;

class PluginMenu
{

    /**
     * 创建菜单
     * @param array $menu
     * @param mixed $parent 父类的name或pid
     */
    public static function create($menu, $pid = MenuConstant::ADDON_PID)
    {
        $allow = array_flip(['title', 'icon', 'href', 'remark']);
        foreach ($menu as $k => $v) {
            $hasChild = isset($v['sublist']) && $v['sublist'] ? true : false;

            $data = array_intersect_key($v, $allow);


            $data['icon'] = isset($data['icon']) ? $data['icon'] : ($hasChild ? 'fa-list' : '');
            $data['pid'] = $pid;


            try {
                $find=SystemMenu::where('title',$data['title'])->where('href',isset($data['href'])?$data['href']:'')->find();
                if($find){
                    $pid1=$find->id;
                }else{
                    $menu = SystemMenu::create($data);
                    $pid1=$menu->id;
                }
                if ($hasChild) {
                    self::create($v['sublist'], $pid1);
                }
            } catch (\Exception $e) {
                throw new \Exception($e->getMessage());
            }
        }
        TriggerService::updateMenu();
        return true;
    }

    /**
     * 删除插件菜单
     * @param string $name 规则name
     * @return boolean
     */
    public static function delete($name)
    {
        if(!$name){
            return false;
        }
        $ids=SystemMenu::where('remark',$name)->column('id');
        if(empty($ids)){
            return true;
        }
        try {
            (new SystemMenu())->destroy($ids);
            TriggerService::updateMenu();
            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

    }

}
